package com.softer.wxzj.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softer.wxzj.common.entity.CommonResult;
import com.softer.wxzj.common.entity.Page;
import com.softer.wxzj.common.enums.MessageEnum;
import com.softer.wxzj.common.enums.NumberEnum;
import com.softer.wxzj.common.enums.ShiroResultEnum;
import com.softer.wxzj.common.error.CourseException;
import com.softer.wxzj.common.util.*;
import com.softer.wxzj.entity.AccKeepAccount;
import com.softer.wxzj.entity.ExpPayReq;
import com.softer.wxzj.entity.ExpProjectReq;
import com.softer.wxzj.entity.SysCoreParam;
import com.softer.wxzj.mapper.*;
import com.softer.wxzj.service.ExpPayForPrintService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

/**
 * @author Gong Zhiyang
 * @date 2019/8/15
 */
@Service
public class ExpPayForPrintServiceImpl implements ExpPayForPrintService {
    @Autowired
    private ExpPayForPrintMapper expPayForPrintMapper;
    @Autowired
    private OperUtil zoneCodeUtil;
    @Autowired
    private SysCoreParamMapper sysCoreParamMapper;
    @Autowired
    private ExpPayReqMapper expPayReqMapper;
    @Autowired
    private AccKeepAccountMapper accKeepAccountMapper;
    @Autowired
    private ExpProjectReqMapper expProjectReqMapper;

    /**
     * 查询付款通知书打印列表
     *
     * @param page      分页实体
     * @param expPayReq 查询实体
     * @return 列表
     */
    @Override
    public PageInfo<ExpPayReq> getExpPayForPrint(Page page, ExpPayReq expPayReq) {
        String zoneCode = zoneCodeUtil.getZoneCode();
        expPayReq.setZoneCode(zoneCode);
        List<ExpPayReq> list;
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        if (StringUtils.isNotEmpty(expPayReq.getFuzzy())) {
            //模糊查詢
            list = expPayForPrintMapper.fuzzyExpPayForPrint(expPayReq);
        } else {
            //精确查询
            list = expPayForPrintMapper.getExpPayForPrint(expPayReq);
        }
        PageInfo<ExpPayReq> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 新建凭证
     *
     * @param expPayReq 拨款凭证信息
     * @return 操作结果
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult credentials(ExpPayReq expPayReq) {
        //查询拨款详情
        ExpPayReq payReq = expPayReqMapper.selectByPrimaryKey(expPayReq.getId());
        payReq.setBankId(expPayReq.getBankId());
        //查询拨款凭证的有效期限为多少天
        SysCoreParam info = sysCoreParamMapper.getInfo(String.valueOf(NumberEnum.TWENTY_TWO.getNum()));
        String paramValue = info.getParamValue();
        if (StringUtils.isEmpty(paramValue)) {
            //如果未设置，默认为10天
            paramValue = String.valueOf(NumberEnum.TEN.getNum());
        }
        //有效到期日
        LocalDate date = DateUtils.getDate(Integer.parseInt(paramValue));
        expPayReq.setValidDate(date.toString());
        payReq.setValidDate(date.toString());
        //生成支付编号
        String payNo = DepositUtil.getNo(NumberEnum.EIGHT.getNum().toString());
        expPayReq.setPayNo(payNo);
        expPayReq.setStep(String.valueOf(NumberEnum.TWO.getNum()));
        expPayReq.setModifier(ShiroUserUtil.getUserName());
        int num = expPayReqMapper.updateByPrimaryKeySelective(expPayReq);
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        //添加到记账表
        addAccKeep(payReq, expPayReq.getPayNo());
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    private void addAccKeep(ExpPayReq payReq, String newPayNo) {
        AccKeepAccount accKeepAccount = new AccKeepAccount();
        String payNo = payReq.getPayNo();
        if (StringUtils.isNotEmpty(payNo)) {
            String id = accKeepAccountMapper.selectByPayNo(payNo);
            if (StringUtils.isNotEmpty(id)) {
                //如果之前存在支付编号，则将记账表中的状态改为废弃
                int num = accKeepAccountMapper.updateState(String.valueOf(NumberEnum.ZERO.getNum()), payNo);
                if (num == NumberEnum.ZERO.getNum()) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                }
            }
        }
        accKeepAccount.setBusiNo(newPayNo);
        accKeepAccount.setBusiType("312");
        accKeepAccount.setCreater(ShiroUserUtil.getUserName());
        accKeepAccount.setBankCode(payReq.getBankId());
        accKeepAccount.setPayAmount(payReq.getSystemPayment());
        accKeepAccount.setAccountState(String.valueOf(NumberEnum.ZERO.getNum()));
        accKeepAccount.setVerificationState(String.valueOf(NumberEnum.ZERO.getNum()));
        accKeepAccount.setState(String.valueOf(NumberEnum.ONE.getNum()));
        accKeepAccount.setReqName(payReq.getGrantreqUser());
        accKeepAccount.setSpecialAccount("325");
        accKeepAccount.setVaildDate(payReq.getValidDate());
        accKeepAccount.setGrantreqNum(payReq.getGrantreqNum());
        ExpProjectReq expProjectReq = expProjectReqMapper.selectByPrimaryKey(payReq.getReqId());
        if (expProjectReq != null) {
            accKeepAccount.setRegionId(expProjectReq.getRegionId());
        }
        StringBuffer str = new StringBuffer(6);
        str.append(expProjectReq.getReqName()).append(",").append(payReq.getReqName());
        accKeepAccount.setRemark(str.toString());
        int insert = accKeepAccountMapper.insert(accKeepAccount);
        if (insert == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
    }

    /**
     * 有效期维护 或者 修改是否打印
     *
     * @param expPayReq 修改实体
     * @return 维护结果
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult update(ExpPayReq expPayReq) {
        expPayReq.setModifier(ShiroUserUtil.getUserName());
        int num = expPayReqMapper.updateByPrimaryKeySelective(expPayReq);
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        //查询拨款详情
        ExpPayReq payReq = expPayReqMapper.selectByPrimaryKey(expPayReq.getId());
        payReq.setValidDate(expPayReq.getValidDate());
        String payNo = payReq.getPayNo();
        String id = accKeepAccountMapper.selectByPayNo(payNo);
        if (StringUtils.isNotEmpty(id)) {
            AccKeepAccount accKeepAccount = new AccKeepAccount();
            accKeepAccount.setBusiNo(payNo);
            accKeepAccount.setVaildDate(expPayReq.getValidDate());
            int count = accKeepAccountMapper.updateValidDate(accKeepAccount);
            if (count == NumberEnum.ZERO.getNum()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
            }
        } else {
            addAccKeep(payReq, payNo);
        }
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }
}
